package com.ztmmm.module.repo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ztmmm.common.dto.PageDto;
import com.ztmmm.common.vo.ApiRest;
import com.ztmmm.common.vo.PageResult;
import com.ztmmm.exception.ServiceException;
import com.ztmmm.module.repo.entity.Repo;
import com.ztmmm.module.repo.mapper.RepoMapper;
import com.ztmmm.module.repo.service.IRepoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 题库 服务实现类
 * </p>
 *
 * @author ztm
 * @since 2023-03-20
 */
@Service
public class RepoServiceImpl extends ServiceImpl<RepoMapper, Repo> implements IRepoService {
    @Autowired
    private RepoMapper repoMapper;

    @Override
    public List<Repo> selectAll() {
        return repoMapper.selectList(new QueryWrapper<Repo>());
    }

    @Override
    public PageResult<Repo> findPage(PageDto<Repo> dto) {
        if (dto == null){
            throw new ServiceException("参数异常");
        }
        if (dto.getNow() == 0){
            throw new ServiceException("参数异常");
        }
        IPage<Repo> page = new Page<>(dto.getNow(),dto.getSize());
        QueryWrapper queryWrapper = new QueryWrapper();
        if (dto.getWhere().getTitle() !=null){
            queryWrapper.like("title",dto.getWhere().getTitle());
        }
        IPage<Repo> iPage = this.page(page,queryWrapper);

        PageResult<Repo> pageResult = new PageResult<>();
        pageResult.setPages(iPage.getPages());
        pageResult.setList(iPage.getRecords());
        pageResult.setTotal(iPage.getTotal());
        return pageResult;
    }

    @Override
    @Transactional
    public ApiRest<Repo> add(Repo repo) {
        if (repo == null){
            throw new ServiceException("参数异常");
        }
        repo.setCreateTime(new Date());
        repo.setUpdateTime(new Date());
        boolean b = this.saveOrUpdate(repo);
        return b ? ApiRest.success() : ApiRest.failure();
    }

    @Override
    public ApiRest<Repo> del(String repoId) {
        if (repoId == null){
            throw new ServiceException("参数异常");
        }
        boolean b = this.removeById(repoId);
        return b ? ApiRest.success() : ApiRest.failure();
    }

    @Override
    public ApiRest<Repo> delAll(String[] s) {
        boolean b = this.removeBatchByIds(Arrays.asList(s));
        return b?ApiRest.success():ApiRest.failure();
    }


}
